package com.lsq.baseadmin.modules.controller;


import com.lsq.baseadmin.common.exception.MyException;
import com.lsq.baseadmin.modules.manage.service.UserService;
import com.lsq.baseadmin.modules.manage.utils.AuthUtil;
import com.lsq.baseadmin.modules.manage.vo.AuthUser;
import com.lsq.baseadmin.modules.manage.vo.UserVo;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author lsq
 * @since 2020-10-22
 */
@Api(tags = "登录")
@RestController
@RequestMapping("/auth")
public class AuthController {

    private UserService userService;

    public AuthController(UserService userService) {
        this.userService = userService;
    }

    @ApiOperation("登录")
    @PostMapping(value = "/login")
    public ResponseEntity<Object> login(@RequestBody AuthUser authUser, HttpSession session){
        String verifyCode = AuthUtil.getVerifyCode(session);
        if (!StringUtils.hasText(verifyCode)) {
            throw new MyException(HttpStatus.PRECONDITION_FAILED, "验证码不存在或已过期");
        }
        if(!StringUtils.hasText(authUser.getCode()) || !authUser.getCode().equals(verifyCode)) {
            throw new MyException(HttpStatus.PRECONDITION_FAILED, "验证码不正确！");
        }
        UserVo loginUser = userService.login(authUser);
        AuthUtil.setLoginUser(loginUser, session);
        return ResponseEntity.ok("");
    }
    @ApiOperation("退出登录")
    @GetMapping(value = "/loginOut")
    public ResponseEntity<Object> loginOut(HttpSession session){
        AuthUtil.removeLoginUser(session);
        return ResponseEntity.ok("");
    }
    @ApiOperation("获取验证码")
    @GetMapping(value = "/captcha")
    public ResponseEntity<Object> getVerifyCodeImage(HttpSession session){
        // 算术类型 https://gitee.com/whvse/EasyCaptcha
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result = captcha.text();
        // 保存
        AuthUtil.setVerifyCode(result, session);
        return ResponseEntity.ok(captcha.toBase64());
    }

}
